/**
 * 团队密钥API接口
 * 
 * @author RickPan Team
 * @version 1.0
 * @since 2025-07-19
 */

import { request } from '@/utils/request'

// 团队密钥响应接口
export interface TeamKeyResponse {
  id: number
  teamId: number
  keyVersion: number
  encryptedKey: string // Base64编码的加密密钥
  algorithm: string
  keyLength: number
  status: 'active' | 'expired' | 'revoked'
  createdBy: number
  creatorName?: string
  expiresAt?: number // 过期时间戳
  createdAt: number // 创建时间戳
  updatedAt: number // 更新时间戳
}

// 密钥健康状态接口
export interface KeyHealthStatus {
  healthy: boolean
  status: 'HEALTHY' | 'EXPIRING_SOON' | 'EXPIRED' | 'NO_KEY'
  message: string
  recommendation: string
  keyVersion?: number
  algorithm?: string
  keyLength?: number
  createdAt?: number
  expiresAt?: number
  isExpired?: boolean
  isExpiringSoon?: boolean
  checkTime: number
}

// 密钥统计信息接口
export interface KeyStatistics {
  totalKeys: number
  activeKeys: number
  maxKeyVersion: number
  statusCounts: Record<string, number>
  currentKeyVersion?: number
  currentKeyCreatedAt?: number
  currentKeyExpiresAt?: number
}

/**
 * 团队密钥API类
 */
class TeamKeyApi {
  /**
   * 获取团队当前活跃密钥
   */
  async getCurrentKey(teamId: number): Promise<TeamKeyResponse> {
    console.log('🔑 获取团队当前密钥:', teamId)
    
    const response = await request.get(`/teams/${teamId}/keys/current`)
    
    if (response.code === 200) {
      console.log('✅ 成功获取团队密钥:', response.data)
      return response.data
    } else {
      console.error('❌ 获取团队密钥失败:', response.message)
      throw new Error(response.message || '获取团队密钥失败')
    }
  }

  /**
   * 获取团队指定版本的密钥
   */
  async getKeyByVersion(teamId: number, keyVersion: number): Promise<TeamKeyResponse> {
    console.log('🔑 获取团队指定版本密钥:', { teamId, keyVersion })
    
    const response = await request.get(`/teams/${teamId}/keys/version/${keyVersion}`)
    
    if (response.code === 200) {
      console.log('✅ 成功获取指定版本密钥:', response.data)
      return response.data
    } else {
      console.error('❌ 获取指定版本密钥失败:', response.message)
      throw new Error(response.message || '获取指定版本密钥失败')
    }
  }

  /**
   * 轮换团队密钥（生成新版本）
   */
  async rotateKey(teamId: number): Promise<TeamKeyResponse> {
    console.log('🔄 开始轮换团队密钥:', teamId)
    
    const response = await request.post(`/teams/${teamId}/keys/rotate`)
    
    if (response.code === 200) {
      console.log('✅ 团队密钥轮换成功:', response.data)
      return response.data
    } else {
      console.error('❌ 团队密钥轮换失败:', response.message)
      throw new Error(response.message || '团队密钥轮换失败')
    }
  }

  /**
   * 初始化团队密钥（首次创建）
   */
  async initializeKey(teamId: number): Promise<TeamKeyResponse> {
    console.log('🚀 初始化团队密钥:', teamId)
    
    const response = await request.post(`/teams/${teamId}/keys/initialize`)
    
    if (response.code === 200) {
      console.log('✅ 团队密钥初始化成功:', response.data)
      return response.data
    } else {
      console.error('❌ 团队密钥初始化失败:', response.message)
      throw new Error(response.message || '团队密钥初始化失败')
    }
  }

  /**
   * 获取团队密钥健康状态
   */
  async getKeyHealth(teamId: number): Promise<KeyHealthStatus> {
    console.log('🏥 检查团队密钥健康状态:', teamId)
    
    const response = await request.get(`/teams/${teamId}/keys/health`)
    
    if (response.code === 200) {
      console.log('✅ 成功获取密钥健康状态:', response.data)
      return response.data
    } else {
      console.error('❌ 获取密钥健康状态失败:', response.message)
      throw new Error(response.message || '获取密钥健康状态失败')
    }
  }

  /**
   * 获取团队密钥统计信息
   */
  async getKeyStatistics(teamId: number): Promise<KeyStatistics> {
    console.log('📊 获取团队密钥统计:', teamId)
    
    const response = await request.get(`/teams/${teamId}/keys/stats`)
    
    if (response.code === 200) {
      console.log('✅ 成功获取密钥统计:', response.data)
      return response.data
    } else {
      console.error('❌ 获取密钥统计失败:', response.message)
      throw new Error(response.message || '获取密钥统计失败')
    }
  }

  /**
   * 批量获取多个团队的密钥（用于预加载）
   */
  async batchGetKeys(teamIds: number[]): Promise<Record<number, TeamKeyResponse>> {
    console.log('📦 批量获取团队密钥:', teamIds)
    
    const results: Record<number, TeamKeyResponse> = {}
    
    // 并发获取所有团队的密钥
    const promises = teamIds.map(async (teamId) => {
      try {
        const key = await this.getCurrentKey(teamId)
        results[teamId] = key
      } catch (error) {
        console.warn(`⚠️ 获取团队${teamId}密钥失败:`, error)
        // 不抛出错误，继续处理其他团队
      }
    })
    
    await Promise.allSettled(promises)
    
    console.log('✅ 批量获取密钥完成:', Object.keys(results).length, '/', teamIds.length)
    return results
  }

  /**
   * 检查密钥是否需要轮换
   */
  async checkKeyRotationNeeded(teamId: number): Promise<{
    needsRotation: boolean
    reason?: string
    recommendation?: string
  }> {
    try {
      const health = await this.getKeyHealth(teamId)
      
      const needsRotation = health.status === 'EXPIRED' || health.status === 'EXPIRING_SOON'
      
      return {
        needsRotation,
        reason: needsRotation ? health.message : undefined,
        recommendation: needsRotation ? health.recommendation : undefined
      }
    } catch (error) {
      console.error('❌ 检查密钥轮换需求失败:', error)
      return {
        needsRotation: true,
        reason: '无法获取密钥状态',
        recommendation: '建议检查密钥配置'
      }
    }
  }

  /**
   * 自动处理密钥轮换（如果需要）
   */
  async autoRotateIfNeeded(teamId: number): Promise<{
    rotated: boolean
    newKey?: TeamKeyResponse
    reason?: string
  }> {
    try {
      const rotationCheck = await this.checkKeyRotationNeeded(teamId)
      
      if (rotationCheck.needsRotation) {
        console.log('🔄 检测到需要轮换密钥，自动执行轮换:', teamId)
        const newKey = await this.rotateKey(teamId)
        
        return {
          rotated: true,
          newKey,
          reason: rotationCheck.reason
        }
      } else {
        return {
          rotated: false,
          reason: '密钥状态正常，无需轮换'
        }
      }
    } catch (error) {
      console.error('❌ 自动密钥轮换失败:', error)
      throw error
    }
  }

  /**
   * 验证密钥格式
   */
  validateKeyFormat(encryptedKey: string): {
    isValid: boolean
    issues: string[]
  } {
    const issues: string[] = []
    
    if (!encryptedKey) {
      issues.push('密钥不能为空')
      return { isValid: false, issues }
    }
    
    // 检查Base64格式
    try {
      const decoded = atob(encryptedKey)
      if (decoded.length < 32) {
        issues.push('密钥长度不足')
      }
    } catch (error) {
      issues.push('密钥格式无效（非Base64）')
    }
    
    return {
      isValid: issues.length === 0,
      issues
    }
  }

  /**
   * 格式化密钥信息用于显示
   */
  formatKeyInfo(key: TeamKeyResponse): {
    displayName: string
    statusText: string
    statusColor: string
    expiryText: string
  } {
    const displayName = `密钥 v${key.keyVersion}`
    
    let statusText = ''
    let statusColor = ''
    
    switch (key.status) {
      case 'active':
        statusText = '活跃'
        statusColor = 'success'
        break
      case 'expired':
        statusText = '已过期'
        statusColor = 'danger'
        break
      case 'revoked':
        statusText = '已撤销'
        statusColor = 'warning'
        break
    }
    
    let expiryText = '永不过期'
    if (key.expiresAt) {
      const expiryDate = new Date(key.expiresAt)
      const now = new Date()
      const diffDays = Math.ceil((expiryDate.getTime() - now.getTime()) / (1000 * 60 * 60 * 24))
      
      if (diffDays < 0) {
        expiryText = `已过期 ${Math.abs(diffDays)} 天`
      } else if (diffDays === 0) {
        expiryText = '今天过期'
      } else if (diffDays <= 7) {
        expiryText = `${diffDays} 天后过期`
      } else {
        expiryText = expiryDate.toLocaleDateString()
      }
    }
    
    return {
      displayName,
      statusText,
      statusColor,
      expiryText
    }
  }
}

// 导出单例实例
const teamKeyApi = new TeamKeyApi()
export default teamKeyApi

// 导出类型
export type { TeamKeyResponse, KeyHealthStatus, KeyStatistics }
